<?php
namespace Home\Controller;

use Think\Controller;
use Home\Controller\PublicController;
use Common\Api\Publicaction;
class UserController extends Controller
{
//    public function admin()
//    {
////        $user=D('user')->getUserByUsername($_SESSION['uid']);
////        if(!isset($user)){
////            $this->error('您尚未登录',U('User/login'),2);
////        }elseif($user['user_type']!='admin') $this->error('您无权限访问',U('Article/index'),2);
//        //注册数据到模板
//    }

    public function index()
    {

        $newest_user_datas=D('User')->getNewestUserByNumber(5);
        $active_user_datas=D('User')->getActiveUserByNumber(5);
//        dump($newest_user_datas);
//        dump($active_user_datas);
        $this->assign('newest_user_datas',$newest_user_datas);
        $this->assign('active_user_datas',$active_user_datas);
        $this->display(T('Home@User/index'));
    }


    public function login()
    {
        if(IS_POST){
            $data=array(
                'username' =>$_POST['username'],
                'password' => $_POST['password'],
                'verify' => $_POST['verify']
            );
//            $Verify =  new \Think\Verify();
//            if(!$Verify->check($_POST['verify'])) return $this->success('验证码错误',U('User/login'),1);
            $db_userdata=D('User')->getUserByUsername($data['username']);
//            dump($data);
//            dump($db_userdata);die;
            if($db_userdata[0]['password']==md5($data['password'])){
                session('uid',$data['username']);
                return $this->success('登录成功',U('Article/index'),1);
            }else{
                return $this->error('账号或密码错误',U('User/login'),1);
            }

        }
        if(session('?uid')&&$_SESSION){
            $this->display('Article/index');
        }
//        $this->assign('verify',$Verify);
        $this->display('User/login');

    }

    public function logout()
    {
        unset($_SESSION['uid']);
        $this->display(T('Home@Article/index'));
    }


    public function rigister()
    {
        if(IS_POST){
            $data=array(
                    'username' =>$_POST['username'],
                    'email' => $_POST['email'],
                    'password' => $_POST['password']
            );
//            $Verify =  new \Think\Verify();
//            if(!$Verify->check($_POST['verify'])) return $this->success('验证码错误',U('User/rigister'),1);
            if(D('User')->checkUsernameExsist($_POST['username']))  $result=['status'=>'error','info'=>'用户名已经存在'];
            if(!$_POST['username'])  $result=['status'=>'error','info'=>'用户名不能为空'];
            if(D('User')->checkEmailExsist($_POST['email']))  $result=['status'=>'error','info'=>'邮箱已存在'];
            if(!$_POST['email'])  $result=['status'=>'error','info'=>'邮箱不能为空'];
            if($_POST['password']=='') $result=['status'=>'error','info'=>'两次密码不一致'];
            if($_POST['password']!=$_POST['password_confirm']) $result=['status'=>'error','info'=>'两次密码不一致'];
            if($result['status']=='error') return $this->error($result['info'],U('User/login'),1);
//            dump(D('User')->addUser($data));die;
            if(!D('User')->addUser($data)) return $this->error('注册失败',U('User/register'),1);
            return $this->success('注册成功',U('User/login'),1);
        }
        $this->display(T('Home@User/rigister'));
    }

    public function findpassword(){
        if(IS_POST){
            $data=array(
                'username' => $_POST['username'],
                'email' => $_POST['email'],
                'verify' => $_POST['verify']
            );
            $user=D('User')->getUserByUsername($data['username']);
            if(!$user || $user['email']==$data['email']) return $this->success('请输入有效的邮箱和用户名',U('User/login'),1);
//            $Verify =  new \Think\Verify();
//            if(!$Verify->check($data['verify'])) return $this->success('验证码错误',U('User/login'),1);
            $password=md5($data['username']);
//            dump($password);die();
            D('User')->updateUserByUsername($data['username'],array('password'=>md5($password)));
            $token=md5($data['username'].$data['email']);
            $to=$data['email'];
            $name=$data['username'];
            $body='密码重置';
            $subject=<<<EOF
		亲爱的{$name}您好~！您的密码已经重置为{$password}<br/>
		请点击此登陆<br/>
		<a href="http://localhost/tp/Home/user/login">{$token}</a>
		<br/>
		如果点此链接无反映，可以将其复制到浏览器中来执行，链接的有效时间为24小时。
EOF;
            $Publicaction=new Publicaction();
            $Publicaction->think_send_mail($to, $name, $subject , $body, $attachment = null);
            $result=['status'=>'success','info'=>'密码已找回详情请看邮箱'];

        }
        return $this->success($result['info'],U('User/login'),1);

        $this->display(T('Home@User/login'));
    }

    public function info()
    {
        $self_url=$_SERVER['PATH_INFO'];
        $id=explode(".",end(explode("/",$self_url)))['0'];
//        dump($_SERVER['PATH_INFO']);
//        dump($_SERVER);die();
        if(!preg_match('/^[\d]+$/',$id)){
//            dump("认为此操作为在线者本人操作,故还需要用session识别用户");
        $user=D('User')->getUserByUsername(session('uid'));
//            dump($user);
        }else{
            $user=D('User')->getUserById($id);
//            dump($user);
            if(!$user){
                $this->error('用户不存在',U('article/index'),1);
            }
        }
        $articles=D('Article')->getArticleByUserId($user[0]['id']);
        foreach ($articles as $key => $article) {
            $sort_data = D('Sort')->getSortById($article['sort_id']);
            $articles[$key]['sort'] = $sort_data[0]['name'];
            $user_data = (D('User')->getUserById($article['author_id']));
            $articles[$key]['author'] = $user_data[0]['username'];
            $comment_data = (D('Comment')->getCommentByArticleIdDesc($articles[$key]['id']));
            $articles[$key]['last_comment'] = $comment_data[0]['content'];
            $articles[$key]['last_comment_user_id'] = $comment_data[0]['from_id'];
            $last_comment_user = (D('User')->getUserById($comment_data[0]['from_id']));
            $articles[$key]['last_comment_user_name'] = $last_comment_user[0]['username'];
            $avatar_data = D('Avatar')->getAvatarById($user_data[0]['id']);
            $articles[$key]['avatar_name'] = $avatar_data[0]['name'];
        }
        $user_info=D('User')->getUserById($user['0']['id']);
        $avatar_data = D('Avatar')->getAvatarByUserId($user['0']['id']);
        $user_info[0]['avatar_name'] = $avatar_data[0]['name'];
        $recent_comments=D('Comment')->getRecentCommentByFromIdDesc($user['0']['id']);
        foreach($recent_comments as $key=>$recent_comment){
            $avatar_data=D('Avatar')->getAvatarByUserId($recent_comment['from_id']);
            $recent_comments[$key]['avatar_name']=$avatar_data[0]['name'];
        }
//        dump($user_info);
//        dump($articles);
//        dump($recent_comments);
        $this->assign('articles',$articles);
        $this->assign('user_info',$user_info);
        $this->assign('recent_comments',$recent_comments);
        $this->display(T('Home@User/info'));
    }

    public function set()
    {
        if(!D('User')->checklogin()) return $this->error('请先登录',U('User/login'),1);
        $user=D('User')->getUserByUsername(session('uid'));
        $avatar_data=D('Avatar')->getAvatarById($user[0]['id']);
        $user[0]['avatar_name']=$avatar_data[0]['name'];
        if(IS_POST){
//            dump($_FILES);
//            dump($_POST);die();
            switch($_POST['type']){
                case 'base_info':
                    $data=array('email'=>$_POST['email'],'signature'=>$_POST['signature'],'introduction'=>$_POST['introduction']);
                    $flag=D('User')->updateUserBaseInfoById($user[0]['id'],$data);
                    break;
                case 'avatar':
                    $data=array('avatar_name'=>$_POST['avatar_name']);
                    $flag=D('Avatar')->updateAvatarByUserId($user[0]['id'],$data);
                    break;
                case 'password':
                    $data=array( 'old_password'=>$_POST['old_password'], 'new_passowrd'=>$_POST['new_passowrd'],'again_new_passowrd'=>$_POST['again_new_passowrd']);
                    $flag=D('User')->updateUserPasswordById($user[0]['id'],$data);
                    break;
                default:  return $this->error('不是合法的表单数据',U('User/set'),1);
            }
            if($flag['status']=='success') return $this->success($flag['info'],U('User/set'),1);
            return $this->error($flag['info'],U('User/set'),2);
        }
        $this->assign('user',$user[0]);
        $this->display(T('Home@User/set'));
    }

}